﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;

using Core.Model.Transmit;
using DapperExtensions;
using DapperExtensions.Mapper;
using log4net;

namespace DataServer.Dao.Transmit
{
    public class TransmitDataDao : BaseDao<TransmitData>
    {
        private readonly ILog _log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
        private static DataItemMapper _dataItemMapper;

        public TransmitDataDao()
        {
            if (_dataItemMapper == null)
            {
                _dataItemMapper = new DataItemMapper();
            }
        }

        protected override string GetTableName()
        {
            if (_dataItemMapper != null)
                return _dataItemMapper.TableName;
            return "transmit_data";
        }

        public TransmitData GetEntityById(string id)
        {
            ConnectResult result = null;
            try
            {
                result = OpenDbConnection();
                var predicate = Predicates.Field<TransmitData>(f => f.Id, Operator.Eq, id);
                TransmitData dataItem = result?.Connection.Get<TransmitData>(predicate);
                return dataItem;
            }
            catch (Exception ex)
            {
                _log.Error(ex.Message);
                return null;
            }
            finally
            {
                if (result != null)
                {
                    CloseDbConnection(result.Name);
                }
            }
        }

        public TransmitDevice GetDeviceById(string id)
        {
            ConnectResult result = null;
            try
            {
                if (string.IsNullOrEmpty(id)) return null;
                result = OpenDbConnection();
                string sql = $"SELECT a.* from transmit_device a,(SELECT * from {GetTableName()} WHERE Id='{id}') b WHERE a.Id = b.DeviceId";
                List<TransmitDevice> devices = result?.Connection.GetList<TransmitDevice>(sql);
                if (devices != null && devices.Count > 0) return devices[0];
                return null;
            }
            catch (Exception ex)
            {
                _log.Error(ex.Message);
                return null;
            }
            finally
            {
                if (result != null)
                {
                    CloseDbConnection(result.Name);
                }
            }
        }

        public TransmitData GetEntityByName(string name)
        {
            ConnectResult result = null;
            try
            {
                result = OpenDbConnection();
                var predicate = Predicates.Field<TransmitData>(f => f.Name, Operator.Eq, name);
                TransmitData dataItem = result?.Connection.Get<TransmitData>(predicate);
                return dataItem;
            }
            catch (Exception ex)
            {
                _log.Error(ex.Message);
                return null;
            }
            finally
            {
                if (result != null)
                {
                    CloseDbConnection(result.Name);
                }
            }
        }

        public List<TransmitData> GetDataItemsByDevId(string devId)
        {
            ConnectResult result = null;
            try
            {
                result = OpenDbConnection();
                var predicate = Predicates.Field<TransmitData>(f => f.DeviceId, Operator.Eq, devId);
                IList<ISort> sort = new List<ISort>();
                sort.Add(new Sort { PropertyName = "Position",Ascending = true});
                IEnumerable<TransmitData> dataItems = result?.Connection.GetList<TransmitData>(predicate, sort);
                return dataItems?.ToList();
            }
            catch (Exception ex)
            {
                _log.Error(ex.Message);
                return null;
            }
            finally
            {
                if (result != null)
                {
                    CloseDbConnection(result.Name);
                }
            }
        }

        public bool DeleteDataItemsByDeviceId(string devId)
        {
            ConnectResult result = null;
            try
            {
                result = OpenDbConnection();
                var predicate = Predicates.Field<TransmitData>(f => f.DeviceId, Operator.Eq, devId);
                return result.Connection.Delete<TransmitData>(predicate);
            }
            catch (Exception ex)
            {
                _log.Error(ex.Message);
                return false;
            }
            finally
            {
                if (result != null)
                {
                    CloseDbConnection(result.Name);
                }
            }
        }

    }
    public sealed class TransmitDataMapper : ClassMapper<TransmitData>
    {
        public TransmitDataMapper()
        {
            Table("transmit_data");
            Map(x => x.Id).Key(KeyType.Assigned);
            Map(x => x.Value).Ignore();
            Map(x => x.CurValue).Ignore();
            Map(x => x.UpdateTime).Ignore();
            Map(x => x.TagObject).Ignore();
            //Ignore this property entirely
            //optional, map all other columns
            AutoMap();
        }
    }
}
